<?php

namespace App\Models\SystemManagement;

use App\Models\CommonModel;
use App\Models\Constant\Errors;
use App\Models\Constant\Fields;
use App\Models\Error;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Session\Store as Session;

class OperationLog extends CommonModel
{
    use SoftDeletes;
    protected $table = 'operation_logs';
    protected $primaryKey = 'id';
    protected $dates = ['deleted_at'];
    public $timestamps = true;

    protected $hidden = ['created_at','updated_at','deleted_at'];

    /**
     * @param $skip
     * @param $take
     * @return mixed
     * 获取所有操作日志
     */
    public static function getData($per){
        $query = self::getTableData(self::class,$per);
        return $query;
    }

    /**
     * @param null $u 操作者
     * @param null $t
     * @return Error|OperationLog
     * 按条件搜索日志记录
     */
    public static function getDataByCondition($u=null,$t=null){
        if(!is_null($u) && is_null($t)){
            $query = self::where(Fields::OPERATOR,$u);
        }
        if(is_null($u) && !is_null($t)){
            $query = self::where(Fields::OP_TIME,'like','%'.$t.'%');
        }
        if(!is_null($u) && !is_null($t)){
            $query = self::where(Fields::OPERATOR,$u)
                ->where(Fields::OP_TIME,'like','%'.$t.'%');
        }
        $query = $query->get();
        return $query;
    }

    /**
     * @param $ids
     * @return Error
     * 批量删除日志记录
     */
    static public function batchDelData($ids){
        //dd(self::withTrashed()->restore());
        $query = self::batchDelTableData($ids,self::class);
        return $query;
    }

    /**
     * @param null $t
     * @return Error
     * 按时间条件删除
     */
    static public function clean($t=null){
        $model = self::where(Fields::OP_TIME,'<',$t)->delete();
        return $model;
    }

    /**
     * @param $content
     * 写入日志
     */
    static public function writeData($method,$route,$action){

        $params = new OperationLog();
        $params->operator = Session('login.username') ? Session('login.username') : 'admin';
        $params->operator_time = date('Y-m-d H:i:s',time());
        $params->ip = getIp();
        $params->record = $action;
        $params->method = $method;
        $params->route = $route;
        $params->save();
    }
}
